<?php
/**
 * 商品评论
 * User: yuanxuncheng
 * Date: 2016-12-21
 * Time: 22:39
 */

namespace app\api\model\dao;

use think\Model;
use think\Db;

class Comment extends Model
{
    //set talbename
    protected $table = 'comment';
    //set primary key
    protected $pk = 'comment_id';


    /**
     * @desc 增加评论
     * @return false|int
     */
    public function addComment($param)
    {
        $this->allowField(true)->save($param);
        return $this->data[$this->pk];
    }

    /**
     * @desc 根据条件获取评论
     * @return false|int
     */
    public function getCommentByCond($conds = [], $fields = [], $offset = 0, $limit = 10000, $orderby = '')
    {
        $this->allowField(true);

        $arrCond = [];
        foreach ($conds as $key => $val) {
            if (in_array($key, $this->field)) {
                $arrCond[$key] = $val;
            }
        }
        empty($arrCond) && $arrCond = '1=1';

        $arrField = [];
        foreach ($fields as $val) {
            if (in_array($val, $this->field)) {
                $arrField[] = $val;
            }
        }
        empty($arrField) && $arrField = $this->field;

        return $this->where($arrCond)->limit($offset, $limit)->order($orderby)->field($arrField)->select();
    }

    public function getCount($conds = [], $filed = 'comment_id')
    {
        $this->allowField(true);
        $arrCond = [];
        foreach ($conds as $key => $val) {
            if (in_array($key, $this->field)) {
                $arrCond[$key] = $val;
            }
        }
        empty($arrCond) && $arrCond = '1=1';
        return Db::table($this->table)->where($arrCond)->count($filed);
    }

    public function getSum($conds = [], $filed = 'comment_rank')
    {
        $this->allowField(true);
        $arrCond = [];
        foreach ($conds as $key => $val) {
            if (in_array($key, $this->field)) {
                $arrCond[$key] = $val;
            }
        }
        empty($arrCond) && $arrCond = '1=1';
        return Db::table($this->table)->where($conds)->sum($filed);
    }

    public function getAddTimeAttr($value)
    {
        return date("Y-m-d H:i:s", $value);
    }
}
